package com.shy.config.aop;

import com.shy.config.common.BaseQuery;
import com.shy.config.util.AuthUtils;
import com.shy.config.util.DataScope;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 切面类
 */
@Component
@Aspect // 切面类
@Slf4j
public class DataScopeAop {
    public static final String POINT_CUT = "@annotation(com.shy.config.util.DataScope)";

    @Around(POINT_CUT)
    public Object before(ProceedingJoinPoint point) {
        Object result = null;
        //获取目标方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取目标方法注解
        DataScope dataScopeAnnotation = signature.getMethod().getDeclaredAnnotation(DataScope.class);
        //获取注解属性值
        String tableAlias = dataScopeAnnotation.tableAlias();
        String tableField = dataScopeAnnotation.tableField();
        //查询当前用户角色
        Set<String> securityUserRoles = AuthUtils.getLoginSecurityUserRoles();
        //判断用户是否用于管理员角色admin
        if (!securityUserRoles.contains("admin")) {
            //当前用户不包含管理员角色，则添加数据权限过滤
            // 获取目标方法参数
            Object params = point.getArgs()[0];
            //获取用户的数据权限
            Integer userId = AuthUtils.getLoginSecurityUserId();
            BaseQuery baseQuery = (BaseQuery) params;
            baseQuery.setFilterSql("and " + tableAlias + "." + tableField + " = " + userId);
        }
        try {
            //执行目标方法
            result = point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
